﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Order : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Session[EClass.ESession.Username.ToString()] == null)
        {
            Response.Redirect(String.Format("Login.aspx?ReturnURL={0}&action={1}", "Order.aspx", EClass.EAction.Login), true);
        }
        ShowShoppingCart();
    }
    private void ShowShoppingCart()
    {
        MyShoppingCart sc = Session["ShoppingCart"] as MyShoppingCart;
        if (sc != null && sc.TotalItems > 0)
        {
            sc.JustifyAvailableProduct();
            GridView1.DataSource = sc;
            GridView1.DataBind();
            Label1.Text = String.Format("{0:N0}đ", sc.TotalPrice);
        }
        else
        {
            Response.Write("<script> alert('Giỏ hàng chưa có sản phẩm.\nVui lòng thêm trước khi muốn đặt hàng') </script>");
            Response.Redirect("Homepage.aspx");
        }
    }

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        SetEnabled(!CheckBox1.Checked);
    }
    private void SetEnabled(bool b)
    {
       TextBox4.Text = !b ?TextBox1.Text : "";
       TextBox5.Text = !b ?TextBox2.Text : "";
       TextBox6.Text = !b ?TextBox3.Text : "";
       TextBox4.Enabled = b;
       TextBox5.Enabled = b;
       TextBox6.Enabled = b;
    }
    protected void ASPxButton1_Click(object sender, EventArgs e)
    {
        MyShoppingCart ms = Session["ShoppingCart"] as MyShoppingCart;
        if(ms == null) return;
        SqlParameter[] _params;
        if(CheckBox1.Checked)
        {
            _params = new[]{
            new SqlParameter("@Username", Session[EClass.ESession.Username.ToString()].ToString()), 
            new SqlParameter("@CustomerName",TextBox1.Text), 
            new SqlParameter("@CustomerAddress",TextBox2.Text), 
            new SqlParameter("@CustomerPhoneNo",TextBox3.Text), 
            new SqlParameter("@Total", ms.TotalPrice)};
        }
        else
        {
            _params = new[]{
            new SqlParameter("@Username", Session[EClass.ESession.Username.ToString()].ToString()), 
            new SqlParameter("@CustomerName",TextBox1.Text), 
            new SqlParameter("@CustomerAddress",TextBox2.Text), 
            new SqlParameter("@CustomerPhoneNo",TextBox3.Text), 
            new SqlParameter("@ReceiverName",TextBox4.Text), 
            new SqlParameter("@ReceiverAddress",TextBox5.Text), 
            new SqlParameter("@ReceiverPhoneNo",TextBox6.Text),
            new SqlParameter("@Total", ms.TotalPrice)};
        }
        ms.UpdateOrder(_params);
        Response.Redirect(String.Format("Message.aspx?action={0}", EClass.EAction.Purchase));
    }
}
